import { provide } from 'vue';
import { Definition } from '@logicflow/core';
import { Menu, InsertNodeInPolyline, MiniMap, SelectionSelect, Snapshot } from '@logicflow/extension';
import { ModelType, ModelerContext, useModeler } from '../useapi';
import rulechainPropertiesPanelConfig from '../models/propertiesPanel';

import NodeModels from '../models/node_model';
import EdgeModels from '../models/edge_model';
import { rule_bases, rule_gateway, rule_server, rule_other } from './config';
import { Config } from './flow-design';

export function getFlowOptions(el: HTMLElement, type: string): Definition {
	const logicflowOptions: Definition = {
		container: el,
		adjustEdgeStartAndEnd: true, //是否允许拖动边的端点来调整连线
		edgeSelectedOutline: false,
		stopScrollGraph: true,
		edgeTextEdit: false,
		stopZoomGraph: true,
		edgeTextDraggable: true,
		adjustNodePosition: true,
		multipleSelectKey: 'meta',
		autoExpand: false, // 节点拖拽到边缘不进行扩充
		overlapMode: 1, //元素重合的堆叠模式
		style: {
			nodeText: {
				overflowMode: 'autoWrap',
			},
		},
		keyboard: {
			enabled: true,
		},
	};
	if (type == 'view') {
		logicflowOptions.isSilentMode = true;
		logicflowOptions.stopZoomGraph = true;
		logicflowOptions.stopMoveGraph = true;
		logicflowOptions.adjustEdge = false;
		logicflowOptions.adjustEdgeStartAndEnd = false;
		logicflowOptions.adjustNodePosition = false;
		logicflowOptions.hideAnchors = true;
	}
	if (type == 'design') {
		logicflowOptions.plugins = [Menu, InsertNodeInPolyline, MiniMap, SelectionSelect, Snapshot];
	}
	return logicflowOptions;
}
// 获取左，右侧panel设置项
export function getPropertiesPanelConfig(): any {
	const configData: Array<Config> = [...rule_bases, ...rule_gateway, ...rule_server, ...rule_other];

	const config: any = {};
	configData.forEach((item: any) => {
		config[item.type] = rulechainPropertiesPanelConfig[item.type] || rulechainPropertiesPanelConfig['default'];
	});
	return config;
}

export function initFlow(): ModelerContext {
	let config = getPropertiesPanelConfig();
	let model: ModelType = {
		name: 'flow',
		label: '',
		defaultEdgeType: '',
		nodeTypes: [],
		edgeTypes: [],
	};
	model.nodeTypes.push(...NodeModels);

	model.defaultEdgeType = 'bezier-link';
	model.edgeTypes?.push(...EdgeModels);

	model.init = (lf) => {
		lf.on('flow:start', () => {
			console.log('我要开始执行流程了');
		});
	};

	const modeler = useModeler(model, config);
	const { propertiesPanel } = modeler;

	console.log('设置成功', modeler);
	provide('modeler_context', modeler);
	provide('modeler_select', propertiesPanel);

	return modeler;
}
